/**
 * 
 */
package com.xbang.attendance.web.action.warehouse.inventoryrecord;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;

import com.xbang.attendance.entity.stock.Inventory;
import com.xbang.attendance.entity.stock.InventoryRecord;
import com.xbang.attendance.entity.system.Region;
import com.xbang.attendance.entity.system.Warehouse;
import com.xbang.attendance.helper.inventory.InventoryHelper;
import com.xbang.attendance.service.InventoryService;
import com.xbang.attendance.service.WarehouseService;
import com.xbang.attendance.utils.DateUtil;
import com.demo2do.lighturl.annotation.Action;
import com.xbang.core.ChildSearchActionSupport;
import com.xbang.core.dao.search.component.SearchComponent;
import com.xbang.core.page.Page;
import com.xbang.core.page.Result;
import com.xbang.core.utils.DateUtils;

/**
 * @author dev.zhang
 * 
 */
public class Search extends ChildSearchActionSupport {

	private static final long serialVersionUID = 8792923545485296635L;

	private static final Log logger = LogFactory.getLog(Search.class);

	@Autowired
	private InventoryService inventoryService;

	private List<InventoryRecord> inventoryRecords = new ArrayList<InventoryRecord>();

	private Warehouse warehouse;

	private String timepart_;

	private Integer year, month;

	
	private InventoryRecord inventoryRecord;

	private Date beginDate;
	private Date endDate;

	private String beginDateString;
	private String endDateString;
	
	
	private String soNumber;
	
	

	/** 排序 */
	private String firstOrder, secondOrder, thirdOrder, firstOrderSort, secondOrderSort, thirdOrderSort;

	public String execute() throws Exception {
		return "search";
	}

	@Action("/warehouse/inventoryrecord/order/do")
	public String doOrder() throws Exception {

		String hqlSentence = "FROM Warehouse warehouse WHERE 1 = 1 ";
		String parameterKey = "eqInventoryRecordWarehouseCode";

		Object value = getSearchParameterValue(parameterKey);
		if (value != null) {
			SearchComponent tmpSearchComponent = new SearchComponent();
			tmpSearchComponent.getParameters().put("eqWarehouseCode", value);
			tmpSearchComponent.getWhereSentences().put("eq.warehouse.code", " AND (warehouse.code = :eqWarehouseCode)");

			List objects = inventoryService.searchForList(hqlSentence, tmpSearchComponent);
			if (objects != null && !objects.isEmpty()) {
				warehouse = (Warehouse) objects.get(0);
			} else {
				return "r:/warehouse/inventoryrecord/list/search";
			}
		} else {
			return "r:/warehouse/inventoryrecord/list/search";
		}

		hqlSentence = "FROM InventoryRecord inventoryrecord WHERE 1 = 1 ";

		searchComponent.resetOrderSentence();

		if (!StringUtils.isEmpty(firstOrder)) {
			searchComponent.addSearchElement(firstOrder, firstOrderSort);
		}
		if (!StringUtils.isEmpty(secondOrder)) {
			searchComponent.addSearchElement(secondOrder, secondOrderSort);
		}
		if (!StringUtils.isEmpty(thirdOrder)) {
			searchComponent.addSearchElement(thirdOrder, thirdOrderSort);
		}

		if (searchComponent.getOrderParameters().isEmpty()) {
			searchComponent.addSearchElement("orderBy.inventoryrecord.operationDate", "DESC");
		}

		Result result = inventoryService.searchByPage(hqlSentence, searchComponent, page);
		inventoryRecords = InventoryHelper.proccessInventoryRecords(result.getItems());
		if (inventoryRecords != null && !inventoryRecords.isEmpty()) {
			for (InventoryRecord tmpInventoryRecord : inventoryRecords) {
				if (tmpInventoryRecord.getPoNumber() != null) {
					inventoryRecord = tmpInventoryRecord;
					break;
				}
			}
		}
		page = result.getPage();

		return "index";
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.opensymphony.xwork2.ActionSupport#execute()
	 */
	@Action("/warehouse/inventoryrecord/list")
	public String index() throws Exception {

		String hqlSentence = "FROM Warehouse warehouse WHERE 1 = 1 ";
		String parameterKey = "eqInventoryRecordWarehouseCode";
		String soDateKey = "geqInventoryrecordOperationDate";

		if (searchComponent.getParameters().containsKey(soDateKey)) {
			Date soDate = (Date) searchComponent.getParameters().get(soDateKey);
			year = DateUtils.getYear(soDate);
			month = DateUtils.getMonth(soDate);
		} else {
			return "r:/warehouse/inventoryrecord/list/search";
		}
		Object value = getSearchParameterValue(parameterKey);
		if (value != null) {
			SearchComponent tmpSearchComponent = new SearchComponent();
			tmpSearchComponent.getParameters().put("eqWarehouseCode", value);
			tmpSearchComponent.getWhereSentences().put("eq.warehouse.code", " AND (warehouse.code = :eqWarehouseCode)");

			List objects = inventoryService.searchForList(hqlSentence, tmpSearchComponent);
			if (objects != null && !objects.isEmpty()) {
				warehouse = (Warehouse) objects.get(0);
			} else {
				return "r:/warehouse/inventoryrecord/list/search";
			}
		} else {
			return "r:/warehouse/inventoryrecord/list/search";
		}

		hqlSentence = "FROM InventoryRecord inventoryrecord WHERE 1 = 1 ";

		if (searchComponent.getOrderParameters().isEmpty()) {
			searchComponent.addSearchElement("orderBy.inventoryrecord.operationDate", "DESC");
		}

		Result result = inventoryService.searchByPage(hqlSentence, searchComponent, page);
		inventoryRecords = InventoryHelper.proccessInventoryRecords(result.getItems());
		if (inventoryRecords != null && !inventoryRecords.isEmpty()) {
			for (InventoryRecord tmpInventoryRecord : inventoryRecords) {
				if (tmpInventoryRecord.getPoNumber() != null) {
					inventoryRecord = tmpInventoryRecord;
					break;
				}
			}
		}
		page = result.getPage();
		return "index";
	}

	/**
	 * @return
	 * @throws Exception
	 */
	@Action("/warehouse/inventoryrecord/search/do")
	public String doSearch() throws Exception {

		if (soNumber != null) {
			SearchComponent tmpSearchComponent = new SearchComponent();
			tmpSearchComponent.addSearchElement("eq.inventoryrecord.poNumber", soNumber);
			List<InventoryRecord> tmpInventoryRecords = inventoryService.searchForList("FROM InventoryRecord inventoryrecord WHERE 1 = 1 ", tmpSearchComponent);
			if (tmpInventoryRecords != null && !tmpInventoryRecords.isEmpty()) {
				InventoryRecord tmpInventoryRecord = tmpInventoryRecords.get(0);
				Date tmpDate = tmpInventoryRecord.getOperationDate();

//				year = DateUtils.getYear(tmpDate);
//
//				if (DateUtils.parseDate("" + DateUtils.getYear(tmpDate) + "-" + DateUtils.getMonth(tmpDate) + "-25", "yyyy-MM-dd").before(tmpDate)) {
//					month = DateUtils.getMonth(tmpDate);
//				} else {
//					month = DateUtils.getMonth(DateUtils.addDateEnum(tmpDate, -1, Calendar.MONTH));
//				}
//				
				inventoryRecord = tmpInventoryRecords.get(0);
				warehouse = inventoryRecord.getWarehouse();
			}
			
		//	Date tmpDate = DateUtils.parseDate("" + year + "-" + month + "-25", "yyyy-MM-dd");
			searchComponent.resetGroupSentence();
			searchComponent.resetOrderSentence();
			searchComponent.resetWhereSentence();
			searchComponent.addSearchElement("gt.inventoryrecord.operationDate", DateUtil.parseDate(DateUtil.getPreviousDay(beginDate), DateUtil.DATETIME_FORMAT));
			searchComponent.addSearchElement("leq.inventoryrecord.operationDate", DateUtil.parseDate(DateUtil.getNextDay(beginDate), DateUtil.DATETIME_FORMAT));
			searchComponent.addSearchElement("eq.inventoryrecord.warehouse.code", warehouse.getCode());
			
			
			String hqlSentence = "FROM InventoryRecord inventoryrecord WHERE 1 = 1 ";

			if (searchComponent.getOrderParameters().isEmpty()) {
				searchComponent.addSearchElement("orderBy.inventoryrecord.operationDate", "DESC");
			}
			Result result = inventoryService.searchByPage(hqlSentence, searchComponent, page);
			inventoryRecords = result.getItems();
			if (inventoryRecords != null && !inventoryRecords.isEmpty()){
				for (InventoryRecord tmpInventoryRecord : inventoryRecords) {
					if (tmpInventoryRecord.getPoNumber() != null){
						inventoryRecord = tmpInventoryRecord;
						break;
					}
				}
			}
			inventoryRecords = InventoryHelper.proccessInventoryRecords(result.getItems());
			page = result.getPage();
			
		}
		
		

		return "index";
	}
	
	/** 供选择的地区 */
	private List<Region> regions = new ArrayList<Region>();
	
	@Action("/warehouse/inventoryrecord/search/filter")
	public String searchFilter()  throws Exception  {
		//regions = inventoryService.getObjects(Region.class);
		return "inventoryrecord-list-search-filter";
	}
	
	private List<String> timeparts;
	
	@Action("/warehouse/inventoryrecord/gettimepart")
	public String getInventoryRecordTimePart(){
		List jsons = new ArrayList();
		HttpServletResponse response = ServletActionContext.getResponse();
		try {
			timeparts = inventoryService.getInventoryRecordTimePart();
			for (String date : timeparts) {
				Map mp = new HashMap();
				mp.put("date", date);
				jsons.add(mp);
			}
		} catch (Exception e) {
			setErrorMessage(e.getMessage());
		}
		JSONArray text = JSONArray.fromObject(jsons);
		try {
			response.getWriter().print(text);
		} catch (IOException e) {
			setErrorMessage(e.getMessage());
		}
		return null;
	}
	
	
	/**
	 * 
	 */
	private void indexModth() {
		if (page == null) {
			page = new Page(10);
		}
		Result result = inventoryService.searchByPage("FROM InventoryRecord ", new HashMap<String, Object>(), page);
		inventoryRecords = result.getItems();
		page = result.getPage();
	}

	@Override
	public void resetCustomerSearchCriteria() {

	}

	/**
	 * @return the inventoryRecords
	 */
	public List<InventoryRecord> getInventoryRecords() {
		return inventoryRecords;
	}

	/**
	 * @param inventoryRecords
	 *            the inventoryRecords to set
	 */
	public void setInventoryRecords(List<InventoryRecord> inventoryRecords) {
		this.inventoryRecords = inventoryRecords;
	}

	/**
	 * @return the warehouse
	 */
	public Warehouse getWarehouse() {
		return warehouse;
	}

	/**
	 * @param warehouse
	 *            the warehouse to set
	 */
	public void setWarehouse(Warehouse warehouse) {
		this.warehouse = warehouse;
	}

	/**
	 * @return the inventoryService
	 */
	public InventoryService getInventoryService() {
		return inventoryService;
	}

	/**
	 * @param inventoryService
	 *            the inventoryService to set
	 */
	public void setInventoryService(InventoryService inventoryService) {
		this.inventoryService = inventoryService;
	}

	/**
	 * @return the firstOrder
	 */
	public String getFirstOrder() {
		return firstOrder;
	}

	/**
	 * @param firstOrder
	 *            the firstOrder to set
	 */
	public void setFirstOrder(String firstOrder) {
		this.firstOrder = firstOrder;
	}

	/**
	 * @return the secondOrder
	 */
	public String getSecondOrder() {
		return secondOrder;
	}

	/**
	 * @param secondOrder
	 *            the secondOrder to set
	 */
	public void setSecondOrder(String secondOrder) {
		this.secondOrder = secondOrder;
	}

	/**
	 * @return the thirdOrder
	 */
	public String getThirdOrder() {
		return thirdOrder;
	}

	/**
	 * @param thirdOrder
	 *            the thirdOrder to set
	 */
	public void setThirdOrder(String thirdOrder) {
		this.thirdOrder = thirdOrder;
	}

	/**
	 * @return the firstOrderSort
	 */
	public String getFirstOrderSort() {
		return firstOrderSort;
	}

	/**
	 * @param firstOrderSort
	 *            the firstOrderSort to set
	 */
	public void setFirstOrderSort(String firstOrderSort) {
		this.firstOrderSort = firstOrderSort;
	}

	/**
	 * @return the secondOrderSort
	 */
	public String getSecondOrderSort() {
		return secondOrderSort;
	}

	/**
	 * @param secondOrderSort
	 *            the secondOrderSort to set
	 */
	public void setSecondOrderSort(String secondOrderSort) {
		this.secondOrderSort = secondOrderSort;
	}

	/**
	 * @return the thirdOrderSort
	 */
	public String getThirdOrderSort() {
		return thirdOrderSort;
	}

	/**
	 * @param thirdOrderSort
	 *            the thirdOrderSort to set
	 */
	public void setThirdOrderSort(String thirdOrderSort) {
		this.thirdOrderSort = thirdOrderSort;
	}

	/**
	 * @return the timepart_
	 */
	public String getTimepart_() {
		return timepart_;
	}

	/**
	 * @param timepart_
	 *            the timepart_ to set
	 */
	public void setTimepart_(String timepart_) {
		this.timepart_ = timepart_;
	}

	/**
	 * @return the year
	 */
	public Integer getYear() {
		return year;
	}

	/**
	 * @param year
	 *            the year to set
	 */
	public void setYear(Integer year) {
		this.year = year;
	}

	/**
	 * @return the month
	 */
	public Integer getMonth() {
		return month;
	}

	/**
	 * @param month
	 *            the month to set
	 */
	public void setMonth(Integer month) {
		this.month = month;
	}

	/**
	 * @return the inventoryRecord
	 */
	public InventoryRecord getInventoryRecord() {
		return inventoryRecord;
	}

	/**
	 * @param inventoryRecord
	 *            the inventoryRecord to set
	 */
	public void setInventoryRecord(InventoryRecord inventoryRecord) {
		this.inventoryRecord = inventoryRecord;
	}

	/**
	 * @return the soNumber
	 */
	public String getSoNumber() {
		return soNumber;
	}

	/**
	 * @param soNumber
	 *            the soNumber to set
	 */
	public void setSoNumber(String soNumber) {
		this.soNumber = soNumber;
	}
	private String number;
	

	public Date getBeginDate() {
		return beginDate;
	}

	public void setBeginDate(Date beginDate) {
		this.beginDate = beginDate;
	}

	public Date getEndDate() {
		return endDate;
	}

	public void setEndDate(Date endDate) {
		this.endDate = endDate;
	}

	public String getBeginDateString() {
		return DateUtils.format(beginDate, "yyyy-MM-dd");
	}

	public void setBeginDateString(String beginDateString) {
		this.beginDateString = beginDateString;
	}

	public String getEndDateString() {
		return DateUtils.format(endDate, "yyyy-MM-dd");
	}

	public void setEndDateString(String endDateString) {
		
		this.endDateString =endDateString;
	}

}
